//
//  KKEmoticonToolBar.swift
//  EmotionKeyBoard
//
//  Created by King.Kong. on 16/5/30.
//  Copyright © 2016年 King.Kong. All rights reserved.
//

import UIKit
import SnapKit

private let baseTag = 1000

class KKEmoticonToolBar: UIStackView {
    
    
    //定义属性 记录选中的按钮
    var currentBtn: UIButton?
    //定义闭包
    var selectedIndexCallBack: ((index: Int) -> ())?
    
    init() {
        super.init(frame: CGRectZero)
        //设置背景颜色
        backgroundColor = UIColor.redColor()
        
        //设置轴
        axis = .Horizontal
        //设置填充方式
        distribution = .FillEqually
        setupUI()
    }
    
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    
    private func setupUI() {
        let packages = KKEmoticonManager.sharedEmoticonTools.packages
        for i in 0..<packages.count {
            let package = packages[i]
            var backImageName = "compose_emotion_table_mid"
            if i == 0 {
                backImageName = "compose_emotion_table_left"
            } else if i == packages.count - 1 {
                backImageName = "compose_emotion_table_right"
            }
            
            addChildButtons(package.title! , backImageName: backImageName, index: i)
        }
        
    }
    
    
    private func addChildButtons(title: String, backImageName: String, index: Int) {
        
        let btn = UIButton()
        btn.tag = index + baseTag
        btn.setTitle(title, forState: .Normal)
        btn.setTitleColor(UIColor.whiteColor(), forState: .Normal)
        btn.setTitleColor(UIColor.darkGrayColor(), forState: .Selected)
        //设置按钮的点击事件
        btn.addTarget(self, action: #selector(KKEmoticonToolBar.btnDidClick(_:)), forControlEvents: .TouchUpInside)
        
        btn.setBackgroundImage(UIImage(named: backImageName + "_normal"), forState: .Normal)
        btn.setBackgroundImage(UIImage(named: backImageName + "_selected"), forState: .Selected)
        //UIStackView添加子视图 不能够使用addSubview
        addArrangedSubview(btn)
        if index == 0 {
            btn.selected = true
            //记录选中的按钮
            currentBtn = btn
        }
        
    }
    
    @objc private func btnDidClick(btn: UIButton) {
        print("按钮被点击")
        //记录
        
        //取消之前按钮的选中状态
        currentBtn?.selected = false
        btn.selected = true
        
        currentBtn = btn
        
        //执行闭包完成回调
        selectedIndexCallBack?(index: btn.tag - baseTag)
    }
    
    func setSelectedBtn(section: Int) {
        //取消之前按钮的选中状态
        //根据section 获取对应的按钮
        //如果tag为 0 取到的是对象的自己
        let btntag = baseTag + section
        let btn = self.viewWithTag(btntag) as! UIButton
        currentBtn?.selected = false
        btn.selected = true
        
        currentBtn = btn

    }
    
    
}
